package com.mystnihon.freeremote.ui.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.mystnihon.freeremote.R;
import com.mystnihon.freeremote.db.DBHelper;
import com.mystnihon.freeremote.db.table.SeedboxTable;
import com.mystnihon.freeremote.ui.AddSeedboxActivity;

public class SeedboxFragment extends DefaultSettingsFragment implements LoaderCallbacks<Cursor> {

	private static final int SEEDBOX_LOADER = 1;
	private static final int ADD_SEEDBOX_REQUEST_CODE = 0x20;
	private static final String RIGHT_PANE_BUNDLE_KEY = "right_pane_bundle_key";

	private SeedboxCursorAdapter mSeedboxCursorAdapter;
	private ListView mListView;
	private View mFragmentContainer;
	private TorrentsListFragment rightFragment;
	private boolean mForAdd = false;

	private OnBackStackChangedListener mBackStackListener = new OnBackStackChangedListener() {

		@Override
		public void onBackStackChanged() {
			Fragment fragment = getFragmentManager().findFragmentById(R.id.fr_seedbox_torrents);
			if (fragment != null) {
				mFragmentContainer.setVisibility(View.VISIBLE);
				mSeedboxCursorAdapter.notifyDataSetChanged();
				System.out.println("[Add] notify dataset hanged/position:" + mSeedboxCursorAdapter.mSelectedSeedboxPosition);

			} else {
				mFragmentContainer.setVisibility(View.GONE);
				if (!mForAdd) {
					mSeedboxCursorAdapter.mSelectedSeedboxPosition = ListView.INVALID_POSITION;
					mSeedboxCursorAdapter.notifyDataSetChanged();
				}
				System.out.println("[Pop] notify dataset hanged/position:" + mSeedboxCursorAdapter.mSelectedSeedboxPosition);
			}
			mForAdd = false;
		}
	};

	public static SeedboxFragment newInstance() {
		SeedboxFragment f = new SeedboxFragment();
		return f;

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_seedboxs, null);
		mListView = (ListView) v.findViewById(R.id.fr_seedbox_list);
		mListView.setEmptyView(v.findViewById(R.id.fr_seedbox_list_empty));
		mFragmentContainer = v.findViewById(R.id.fr_seedbox_torrents);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mSeedboxCursorAdapter = new SeedboxCursorAdapter(getSherlockActivity(), null, SeedboxCursorAdapter.NO_SELECTION);
		mSeedboxCursorAdapter.onRestoreInstanceState(savedInstanceState);

		mListView.setAdapter(mSeedboxCursorAdapter);
		mListView.setOnItemLongClickListener(mSeedboxCursorAdapter);
		mListView.setOnItemClickListener(mSeedboxCursorAdapter);
		
		getSherlockActivity().getSupportLoaderManager().initLoader(SEEDBOX_LOADER, savedInstanceState, this);
		if (savedInstanceState != null) {
			if (savedInstanceState.getBoolean(RIGHT_PANE_BUNDLE_KEY, false)) {
				mFragmentContainer.setVisibility(View.VISIBLE);
			}
			Fragment frag = getFragmentManager().findFragmentById(R.id.fr_seedbox_torrents);
			if (frag != null && frag instanceof TorrentsListFragment) {
				rightFragment = (TorrentsListFragment) frag;
			}
		}
		getFragmentManager().addOnBackStackChangedListener(mBackStackListener);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.menu_add_seedbox, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.fr_menu_add_seedbox:
			addNewSeedbox();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int loaderId, Bundle bundle) {
		CursorLoader c = new CursorLoader(getSherlockActivity(), SeedboxTable.CONTENT_URI, SeedboxTable.CONTENT_PROJECTION, null, null, null);
		return c;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		mSeedboxCursorAdapter.swapCursor(cursor);

	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		mSeedboxCursorAdapter.swapCursor(null);

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == ADD_SEEDBOX_REQUEST_CODE) {
			getSherlockActivity().getSupportLoaderManager().restartLoader(SEEDBOX_LOADER, null, this);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean(RIGHT_PANE_BUNDLE_KEY, mFragmentContainer.getVisibility() == View.VISIBLE);
		mSeedboxCursorAdapter.onSaveInstanceState(outState);
	}

	@Override
	public void setMenuVisibility(boolean menuVisible) {
		super.setMenuVisibility(menuVisible);
		if (rightFragment != null) {
			rightFragment.setMenuVisibility(menuVisible);
		}
	}

	private void addNewSeedbox() {
		startActivityForResult(new Intent(getSherlockActivity(), AddSeedboxActivity.class), ADD_SEEDBOX_REQUEST_CODE);
	}

	private void editSeedbox(SeedboxTable sdb) {
		Intent intent = new Intent(getSherlockActivity(), AddSeedboxActivity.class);
		intent.putExtra(AddSeedboxActivity.SEEDBOX_DATA, sdb);
		startActivityForResult(intent, ADD_SEEDBOX_REQUEST_CODE);
	}

	private void deleteSeedbox(final SeedboxTable sdb) {
		final Context ctx = getSherlockActivity();
		AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
		builder.setMessage(R.string.seedbox_dialog_remove).setTitle(getString(R.string.seedbox_dialog_remove_title, sdb.mName)).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				DBHelper.deleteSeedbox(ctx.getContentResolver(), sdb.mId);
				dialog.dismiss();

			}
		}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();

			}
		}).setOnCancelListener(new DialogInterface.OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				dialog.dismiss();

			}
		});
		builder.show();
	}

	private class ViewHolder {
		TextView mTitle;
		// TextView mHost;
	}

	private class SeedboxCursorAdapter extends CursorAdapter implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
		private static final String SAVED_STATE_POSITION = "com.mystnihon.freeremote.mSelectedItem";
		public int mSelectedSeedboxPosition = AdapterView.INVALID_POSITION;
		private LayoutInflater mInflater;

		public SeedboxCursorAdapter(Context context, Cursor c, int flags) {
			super(context, c, flags);
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void onSaveInstanceState(Bundle outState) {
			if (outState != null)
				outState.putInt(SAVED_STATE_POSITION, mSelectedSeedboxPosition);
		}

		public void onRestoreInstanceState(Bundle savedInstanceState) {
			if (savedInstanceState != null)
				mSelectedSeedboxPosition = savedInstanceState.getInt(SAVED_STATE_POSITION);
		}

		@Override
		public void bindView(View convertView, Context ctx, Cursor cursor) {
			ViewHolder viewHolder = (ViewHolder) convertView.getTag();
			final int position = cursor.getPosition();
			final SeedboxTable sdb = SeedboxTable.inflateObject(cursor);

			setData(convertView, viewHolder, sdb, position);
		}

		@Override
		public View newView(Context ctx, Cursor cursor, ViewGroup viewGroup) {
			ViewHolder viewHolder = new ViewHolder();
			final View convertView = mInflater.inflate(R.layout.listitem_seedbox_name, null);
			final int position = cursor.getPosition();
			final SeedboxTable sdb = SeedboxTable.inflateObject(cursor);
			viewHolder.mTitle = (TextView) convertView.findViewById(R.id.fr_seedbox_name);
			convertView.setTag(viewHolder);
			setData(convertView, viewHolder, sdb, position);
			return convertView;
		}

		@Override
		public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {

			FragmentManager fm = getFragmentManager();
			fm.popBackStack();
			FragmentTransaction ft = fm.beginTransaction();
			rightFragment = TorrentsListFragment.newInstance();
			Bundle bundle = new Bundle();
			bundle.putParcelable(TorrentsListFragment.ARGS_SEEDBOX, mSeedboxCursorAdapter.getSelectedSeedbox(position));
			rightFragment.setArguments(bundle);
			ft.addToBackStack(null);
			ft.replace(R.id.fr_seedbox_torrents, rightFragment, TorrentsListFragment.class.getSimpleName());
			ft.commit();
			System.out.println("Add fragment and change position/position:" + mSelectedSeedboxPosition);
			mForAdd = true;
			mSelectedSeedboxPosition = position;
			notifyDataSetChanged();
			System.out.println("Notify change position/position:" + mSelectedSeedboxPosition);
		}

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

			getSherlockActivity().startActionMode(new SeedboxActionModes(position));
			return true;
		}

		public SeedboxTable getSelectedSeedbox(int position) {
			final Cursor c = getCursor();
			final int oldPosition = c.getPosition();
			if (c.moveToPosition(position)) {
				SeedboxTable sdb = SeedboxTable.inflateObject(c);
				c.moveToPosition(oldPosition);
				return sdb;
			}
			return null;

		}

		private void setData(View view, ViewHolder viewHolder, SeedboxTable seedbox, int position) {
			viewHolder.mTitle.setText(seedbox.mName);
			if (position == mSelectedSeedboxPosition) {
				viewHolder.mTitle.setBackgroundResource(R.drawable.btn_rdio_bg_settings_selected);

			} else {
				viewHolder.mTitle.setBackgroundResource(R.drawable.btn_rdio_settings_bg);
			}
		}

	}

	private final class SeedboxActionModes implements ActionMode.Callback {

		public static final int EDIT = Menu.FIRST;
		public static final int DELETE = Menu.FIRST + 1;
		private int mSelectedItem = 0;

		public SeedboxActionModes(int selectedItem) {
			super();
			mSelectedItem = selectedItem;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			handlerAction(item.getItemId());
			mode.finish();
			return true;
		}

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {

			menu.add(0, EDIT, 1, R.string.seedbox_edit).setIcon(R.drawable.content_edit).setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM);
			menu.add(0, DELETE, 2, R.string.seedbox_remove).setIcon(R.drawable.content_discard).setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		private void handlerAction(int menuId) {
			switch (menuId) {
			case EDIT:
				editSeedbox(mSeedboxCursorAdapter.getSelectedSeedbox(mSelectedItem));
				break;
			case DELETE:
				deleteSeedbox(mSeedboxCursorAdapter.getSelectedSeedbox(mSelectedItem));
				break;

			default:
				Toast.makeText(getSherlockActivity(), "Action unknown", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	}

}
